package Timer;

import java.util.PriorityQueue;


/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 38917
 * Date: 2025-03-08
 * Time: 23:56
 */
class MyTimerTask implements Comparable<MyTimerTask>{
    private final Runnable runnable;
    private final long time;

    public MyTimerTask(Runnable runnable,long delay){
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }

    public long getTime(){
        return this.time;
    }

    public void run(){
        runnable.run();
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int)(this.time - o.time);
    }
}

class MyTimer{
    private final PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();
    private final Object locker = new Object();

    public void schedule(Runnable runnable,long delay){
        synchronized (locker) {
            MyTimerTask myTimerTask = new MyTimerTask(runnable, delay);
            queue.offer(myTimerTask);
            locker.notify();
        }
    }

    public MyTimer(){
        Thread thread = new Thread(()->{
            while (true) {
                try {
                    synchronized (locker) {
                        while (queue.isEmpty()) {
                            locker.wait();
                        }
                        MyTimerTask myTimerTask = queue.peek();
                        long curTime = System.currentTimeMillis();
                        if (curTime >= myTimerTask.getTime()){
                            queue.poll();
                            myTimerTask.run();
                        }else {
                            locker.wait(myTimerTask.getTime() - curTime);
                        }
                    }
                }catch (InterruptedException e){
                    throw new RuntimeException();
                }
            }
        });
        thread.setDaemon(true);
        thread.start();
    }
}

public class TestTimer {
    public static void main(String[] args) throws InterruptedException {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(()-> System.out.println("执行：3000"),3000);
        myTimer.schedule(()-> System.out.println("执行：2000"),2000);
        myTimer.schedule(()-> System.out.println("执行：1000"),1000);

        Thread.sleep(4000);
        System.out.println("主线程结束");
    }
}
